package com.bfxy.disruptor;
import java.util.concurrent.TimeUnit;
import java.util.Collection;

public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    private final Sync sync;//同步变量。Sync里面有共享资源state 和 先进先出的队列。

    abstract static class Sync extends AbstractQueuedSynchronizer /*AQS*/ {
        private static final long serialVersionUID = -5179523762034025860L;

        abstract void lock();

        //非公平锁尝试获取锁
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

        //尝试释放锁
        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            //调用这个方法的线程就是获取这个独占锁的线程
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {//state为0
                free = true;//获取锁的线程释放完了，就没有线程获得了这个锁。
                setExclusiveOwnerThread(null);
            }
            setState(c);//减一后的值
            return free;//这个线程还占有这个锁，只是减一了。
        }

        //当前线程是否是拥有这个锁的线程
        protected final boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        ///不为0就返回当前独占线程。为0表示没有线程获取这个锁。
        //有线程获取这个锁就加1，
        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        //
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        //是否上锁，为0表示没有线程调用lock()方法获取这个锁。
        final boolean isLocked() {
            return getState() != 0;
        }

        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
    }

    //非公平锁
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        final void lock() {
        	//线程进来不排队了，谁成功了就获取这把锁
            if (compareAndSetState(0, 1))
            	//设置锁的线程
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        //某个线程获取公平锁，传进来1，
        //没人拥有这把锁，并且队列没人，这个线程就获取到锁，并且设置这个线程为获取这个锁的线程。
        //没人获取这个锁，但是队列有人，不能获取锁。
        //有人有这个锁，但是之前获取锁的线程又是这个线程，也能获取锁，state加1。
        //有人有这个锁，但是之前获取锁的线程不是这个线程，不能获取锁。state不加1。
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();//返回state，
            if (c == 0) {//等于0就能去获取这个锁，就是没有人获取这个锁，但是有可能是刚刚释放锁,但是还有别人在排队。
            	//hasQueuedPredecessors()为false就是队列没有人，compareAndSetState原来是0，现在置为1，
            	//hasQueuedPredecessors()为true就是队列有别人，
                if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);//把当前线程设置成获取了这个锁的线程，
                    return true;//返回true，就是获取这个锁成功。
                }
            }
            //重入锁功能，这个线程再次获取这个锁。
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;//1+1=2
                if (nextc < 0)//不可能小于0
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);//同一个线程获取了几次锁就要释放几次锁。
                return true;
            }
            return false;
        }
    }

    public ReentrantLock() {
        sync = new NonfairSync();
    }

    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

    public void lock() {
        sync.lock();
    }

    /*public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }*/

    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    /*public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }*/

    public void unlock() {//解锁
        sync.release(1);
    }

    public int getHoldCount() {
        return sync.getHoldCount();
    }

    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    public boolean isLocked() {
        return sync.isLocked();
    }

    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    protected Thread getOwner() {
        return sync.getOwner();
    }

    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    public String toString() {
        Thread o = sync.getOwner();
        return super.toString() + ((o == null) ?
                                   "[Unlocked]" :
                                   "[Locked by thread " + o.getName() + "]");
    }
}
